import { HomePage } from './../home/home';
import { Component, ChangeDetectorRef } from "@angular/core";
import {
    NavController,
    AlertController,
    NavParams,
    ActionSheetController,
    LoadingController,
    ToastController
} from "ionic-angular";
import { Storage } from "@ionic/storage";
import { HttpService } from "../../providers/http.service";
import { CommonFunc } from "../../providers/commonFunc";
import { appConfig } from '../../providers/config';
import { CameraOptions, Camera } from "@ionic-native/camera";
import { FileUploadOptions, FileTransferObject, FileTransfer } from "@ionic-native/file-transfer";
import { PhotoViewer } from "@ionic-native/photo-viewer";

@Component({
    templateUrl: "face-update.html",
    providers: [HttpService, CommonFunc]
})
export class FaceUpdatePage {
    appConfig = appConfig
    userId: any;
    faceList = [];
    oldfaceUrl: any;
    constructor(
        public navCtrl: NavController,
        private storage: Storage,
        private httpService: HttpService,
        private alert: AlertController,
        private camera: Camera,
        private commonFunc: CommonFunc,
        private transfer: FileTransfer,
        private photoViewer: PhotoViewer,
        private actionSheet: ActionSheetController,
        public cd: ChangeDetectorRef,
        private navParams: NavParams,
        private loading: LoadingController,
        private toast: ToastController
    ) {
        this.storage.get('user').then(val => {
            this.userId = val.id;
            if (val.faceUrl) {
                this.oldfaceUrl = val.faceUrl
                this.faceList.push(val.faceUrl)
            }
        });

    }

    doSubmit() {
        if (this.faceList.length == 1) {
            let load = this.loading.create({
                spinner: appConfig.spinner,
                duration: appConfig.timeout
            });
            if (this.oldfaceUrl != this.faceList[0]) {
                let param = {
                    id: this.userId,
                    faceUrl: this.faceList[0]
                }
                this.httpService.updateUserFace(param).subscribe(data => {
                    if (data.status == 200) {
                        let tt = this.toast.create({
                            message: "设置成功",
                            duration: 2000,
                            position: "top"
                        });
                        tt.present().then(() => {
                            this.navCtrl.setRoot(HomePage);
                        });
                    }
                })
            } else {
                this.navCtrl.setRoot(HomePage);
            }
        } else {
            this.alert.create({
                title: '提醒',
                message: '请拍照',
                enableBackdropDismiss: false,
                buttons: [
                    {
                        text: '确定',
                        handler: () => {
                            this.presentActionSheet('c');
                        }
                    }
                ]
            }).present();
            return;
        }
    }

    presentActionSheet(i) {
        let buttonList: any = [];
        buttonList.push({
            text: "拍照",
            role: "拍照",
            handler: () => {
                let options: CameraOptions = {
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == "c") {
                                this.faceList.push(imageData);
                            } else {
                                this.faceList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        //let serverUrl =  encodeURI('http://192.168.43.242:8080/upload/base.ctrl');
                        options.fileKey = "file";
                        options.fileName = "test.jpg";
                        options.mimeType = "image/jpeg";
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul["response"]);
                            if (aa["status"] == 200) {
                                if (aa["data"].length > 0) {
                                    if (i == "c") {
                                        this.faceList.push(aa["data"]);
                                    } else {
                                        this.faceList[i] = aa["data"];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });
        buttonList.push({
            text: "从相册选择照片",
            role: "从相册选择照片",
            handler: () => {
                let options: CameraOptions = {
                    sourceType: 0,
                    quality: 85, // destinationType: this.camera.DestinationType.DATA_URL,
                    // encodingType: this.camera.EncodingType.JPEG,
                    mediaType: this.camera.MediaType.PICTURE,
                    targetWidth: 1500,
                    targetHeight: 1500,
                    correctOrientation: true
                };
                this.camera.getPicture(options).then(
                    imageData => {
                        if (!this.commonFunc.hasNetWork()) {
                            if (i == "c") {
                                this.faceList.push(imageData);
                            } else {
                                this.faceList[i] = imageData;
                            }
                            return;
                        }
                        const options: FileUploadOptions = {};
                        let serverUrl = encodeURI(appConfig.IP_URL + appConfig.API.upload);
                        options.fileKey = "file";
                        options.fileName = "test.jpg";
                        options.mimeType = "image/jpeg";
                        const fileTransfer: FileTransferObject = this.transfer.create();
                        fileTransfer.upload(imageData, serverUrl, options).then(restul => {
                            let aa = JSON.parse(restul["response"]);
                            if (aa["status"] == 200) {
                                if (aa["data"].length > 0) {
                                    if (i == "c") {
                                        this.faceList.push(aa["data"]);
                                    } else {
                                        this.faceList[i] = aa["data"];
                                    }
                                }
                            }
                            this.cd.detectChanges();
                        });
                    },
                    err => {
                        // Handle error
                    }
                );
            }
        });

        buttonList.push({
            text: "取消",
            role: "取消",
            handler: () => { }
        });

        let actionSheet = this.actionSheet.create({ buttons: buttonList });
        actionSheet.present();
    }

    onHold(param) {
        let actionSheet = this.actionSheet.create({
            buttons: [
                {
                    text: "重拍",
                    role: "重拍",
                    handler: () => {
                        let i = this.faceList.indexOf(param);
                        this.presentActionSheet(i);
                    }
                },
                {
                    text: "查看大图",
                    role: "查看大图",
                    handler: () => {
                        let url: string = param;
                        this.photoViewer.show(
                            encodeURI(
                                this.appConfig.IP_URL + this.appConfig.API.getUpload + url
                            ).replace("%5C", "/"),
                            null,
                            { share: false }
                        );
                    }
                },
                {
                    text: "删除",
                    handler: () => {
                        let i = this.faceList.indexOf(param);
                        this.faceList.splice(i, 1);
                    }
                },
                {
                    text: "取消",
                    role: "取消",
                    handler: () => {
                        //console.log('Cancel clicked');
                    }
                }
            ]
        });
        actionSheet.present();
    }


}